package com.bupt.ilink.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.bupt.ilink.entity.User;

import com.bupt.ilink.entity.pojo.store.StoreFlowInfo;
import com.bupt.ilink.entity.userManagement.DTO.RoleStatistics;
import com.bupt.ilink.entity.userManagement.DTO.UserMetaResponse;
import com.bupt.ilink.entity.userManagement.DTO.UserTeamResponse;
import com.bupt.ilink.entity.userManagement.TeamFiles;
import com.bupt.ilink.entity.userManagement.UserRoles;
import com.bupt.ilink.entity.userManagement.UserTeam;
import com.bupt.ilink.entity.userManagement.UserTeamPermissions;
import com.bupt.ilink.mapper.userManagement.TeamMapper;
import com.bupt.ilink.mapper.userManagement.UserConnectTeamsMapper;
import com.bupt.ilink.mapper.userManagement.UserTeamPermissionsMapper;
import com.bupt.ilink.utils.R;
import com.bupt.ilink.service.impl.TeamServiceImpl;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.bind.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

//用于管理用户体系，团队空间那些
@RestController
@RequestMapping("/TeamSpace")
public class TeamController {
    @Autowired
    private TeamServiceImpl teamService;

    @Autowired
    private UserConnectTeamsMapper userConnectTeamsMapper;

    @Autowired
    private UserTeamPermissionsMapper userTeamPermissionsMapper;

    @Autowired
    private TeamMapper userTeamMapper;

    //创建团队,前端传入name，team_typeENUM('团队','班级')即可,会初始化一个团队对应的文件夹
    @PostMapping("/CreateTeam")//我要的是RequestParam AuthenticationPrincipal能替换为什么
    public R createTeam(@AuthenticationPrincipal UserDetails userDetails, @RequestParam String name, @RequestParam String team_type, @RequestParam String team_introduction) {
        try {
            User user = (User) userDetails;
            Long teamId = teamService.CreateNewteam(name, team_type,user.getUserId(),team_introduction);
            if (teamId != null) {
                return R.ok("团队创建成功，您已成为队长。", teamId);
            } else {
                return R.failure("团队创建失败");
            }
        } catch (Exception e) {
            return R.failure(e.getMessage());
        }
    }

    //用户获取团队列表：每个团队的名称 人数 以及角色
    @GetMapping("/getTeamList")
    public R getTeamList(@AuthenticationPrincipal UserDetails userDetails) {
        try {
            User user = (User) userDetails;
            List<UserTeamResponse> userResponse = teamService.getTeamList(user.getUserId());
            return R.ok(userResponse);
        } catch (Exception e) {
            return R.failure(e.getMessage());
        }
    }
    //参加的团队
    @GetMapping("/getTeamadd")
    public R getTeamadd(@AuthenticationPrincipal UserDetails userDetails) {
        try {
            User user = (User) userDetails;
            List<UserTeamResponse> userResponse = teamService.getTeamList(user.getUserId());
            return R.ok(userResponse);
        } catch (Exception e) {
            return R.failure(e.getMessage());
        }
    }

    //自己创建的团队,依托表User_team
    @GetMapping("/getTeamCreatedByself")
    public R getTeamCreatedByself(@AuthenticationPrincipal UserDetails userDetails) {
        try {
            User user = (User) userDetails;
            List<UserTeamResponse> userResponse = teamService.getTeamListCreatedByself(user.getUserId());
            return R.ok(userResponse);
        } catch (Exception e) {
            return R.failure(e.getMessage());
        }
    }


    //加入的班级
    @GetMapping("/getClassadd")
    public R getClassadd(@AuthenticationPrincipal UserDetails userDetails) {
        try {
            User user = (User) userDetails;
            List<UserTeamResponse> userResponse = teamService.getClassadd(user.getUserId());
            return R.ok(userResponse);
        } catch (Exception e) {
            return R.failure(e.getMessage());
        }
    }



    //进入空间

    //添加成员
    //单个添加

    //批量添加
    @PostMapping("/addTeamMembers")
    public R addTeamMembers(@RequestParam Long teamId, @RequestBody List<String> userIds) {
        try {
            boolean add = teamService.addTeamMembers(teamId, userIds);
            if (add) {
                return R.ok("添加成功");
            } else {
                return R.failure("添加失败");
            }
        } catch (Exception e) {
            return R.failure(e.getMessage());
        }
    }
    //查询邀请码
    @GetMapping("/getInvitationCode")
    public R getInvitationCode(@RequestParam Long teamId) {
        try {
            String invitationCode = teamService.getInvitationCode(teamId);
            return R.ok(invitationCode);
        } catch (Exception e) {
            return R.failure(e.getMessage());
        }
    }
    //邀请码邀请
    @PostMapping("/addTeamMembersByInvitationCode")
    public R addTeamMembersByInvitationCode(@RequestParam String userId, @RequestParam String invitationCode) {
        try {
            boolean add = teamService.joinTeamByInvitationCode(userId, invitationCode);
            if (add) {
                return R.ok("添加成功");
            } else {
                return R.failure("添加失败");
            }
        } catch (Exception e) {
            return R.failure(e.getMessage());
        }
    }
    //生成邀请码
    @PostMapping("/generateInvitationCode")
    public R generateInvitationCode(@RequestParam Long teamId) {
        try {
            String invitationCode = teamService.generateInvitationCode(teamId);
            return R.ok(invitationCode);
        } catch (Exception e) {
            return R.failure(e.getMessage());
        }
    }
    //邀请码有效性检查
    @PostMapping("/checkInvitationCode")
    public R checkInvitationCode(@RequestParam String invitationCode) {
        try {
            boolean valid = teamService.isInvitationCodeValid(invitationCode);
            return R.ok(valid);
        } catch (Exception e) {
            return R.failure(e.getMessage());
        }
    }

    //邮箱邀请

    //进入成员管理：左侧递归展现部门，右边展现对应成员信息
    //获取团队部门信息
    @GetMapping("/getTeamDepartment")
    public R getTeamDepartment(@AuthenticationPrincipal UserDetails userDetails, @RequestParam Long teamId) {
        try {
            User user = (User) userDetails;
            return teamService.getTeamDepartment(user.getUserId(), teamId);
        } catch (Exception e) {
            return R.failure(e.getMessage());
        }
    }

    //获取团队成员信息
    @GetMapping("/getTeamMembers")
    public R getTeamMembers(@AuthenticationPrincipal UserDetails userDetails,
                            @RequestParam Long teamId,
                            @RequestParam Long groupId,//findGroupIdByUserIdAndTeamId(
                            @RequestParam(required = false,defaultValue = "") String keyword, // 过滤关键字
                            @RequestParam(defaultValue = "1") int currentPage, // 当前页码
                            @RequestParam(defaultValue = "10") int pageSize // 每页数量
                            ) {
        try {
            User user = (User) userDetails;
            Map<String,Object> userResponse = teamService.getTeamMembers(user.getUserId(), teamId,groupId, currentPage, pageSize,keyword);
            return R.ok(userResponse);
        } catch (Exception e) {
            return R.failure(e.getMessage());
        }
    }

    //添加部门


    //角色管理：左侧展现角色及其人数 右边展现角色
    //获取团队中有的角色类型和对应的人数
    @GetMapping("/getTeamRoles")
    public R getTeamRoles(@AuthenticationPrincipal UserDetails userDetails,@RequestParam Long teamId) {
        try {
            User user = (User) userDetails;
            List<RoleStatistics> teamRoles = teamService.getRoleStatisticsByTeamId(teamId);
            if (teamRoles==null){
                return R.failure("该团队没有角色");
            }
            Map<String,Object> result=new HashMap<>();
            result.put("teamRoles",teamRoles);

            Boolean hasMemberManagement = userConnectTeamsMapper.getMemberManagementByUserIdAndTeamId(user.getUserId(), teamId);
            UserTeamPermissions userTeamPermissions = userTeamPermissionsMapper.selectOne(new QueryWrapper<UserTeamPermissions>().eq("team_id", teamId).eq("user_id", user.getUserId()));
            //同时确认个人的管理权限
            if (hasMemberManagement==null){
                hasMemberManagement=false;
            }
            //如果有个人管理权限
            if (userTeamPermissions!=null){
                hasMemberManagement=hasMemberManagement || userTeamPermissions.getMemberManagement();
            }

            result.put("memberManagement",hasMemberManagement);

            if (hasMemberManagement) {
                result.put("roleMessage",teamService.getRoleMessage(teamId));
            }else {
                result.put("roleMessage",teamService.getRoleStatisticsMessage(teamId,teamRoles));
            }

            return R.ok(result);
        } catch (Exception e) {
            return R.failure(e.getMessage());
        }
    }


    //根据角色类型获取团队成员的角色信息
//    @GetMapping("/getTeamMembersRole")
//    public R getTeamMembersRole(
//                                @RequestParam Long teamId,
//                                @RequestParam String roleName
//                                ) {
//        try {
////            User user = (User) userDetails;
//            List<UserMetaResponse> teamRoles = teamService.(null, teamId,null);
//            return R.ok(teamRoles);
//        } catch (Exception e) {
//            return R.failure(e.getMessage());
//        }
//    }


    //从团队中删除队员
    @PostMapping("/removeUserFromTeam")
    public R removeUserFromTeam(
                                @RequestParam Long teamId,
                                @RequestParam String userId
                                ) {
        try {
            boolean quit = teamService.quitTeam(userId, teamId);
            if (quit) {
                return R.ok("退出团队成功");
            } else {
                return R.failure("退出团队失败");
            }
        } catch (Exception e) {
            return R.failure(e.getMessage());
        }
    }

    //用户页面退出团队:删除与团队的关联，同时删除与资源的连接，,团队创建者必须只有他一个人时可以删除，
    @PostMapping("/quitTeam")
    public R quitTeam(@AuthenticationPrincipal UserDetails userDetails, @RequestParam Long teamId) {
        try {
            User user = (User) userDetails;
            boolean quit = teamService.quitTeam(user.getUserId(), teamId);
            if (quit) {
                return R.ok("退出团队成功");
            } else {
                return R.failure("退出团队失败");
            }
        } catch (Exception e) {
            return R.failure(e.getMessage());
        }
    }
    //解散团队

    //删除团队：
    @PostMapping("/deleteTeam")
    public R deleteTeam(@AuthenticationPrincipal UserDetails userDetails, @RequestParam Long teamId) {
        try {
//            User user = (User) userDetails;
            UserTeam team=userTeamMapper.selectOne(new QueryWrapper<UserTeam>().eq("team_id",teamId));
            boolean quit = teamService.removeTeam(team);
            if (quit) {
                return R.ok("退出团队成功");
            } else {
                return R.failure("退出团队失败");
            }
        } catch (Exception e) {
            return R.failure(e.getMessage());
        }
    }

    //添加角色
    @PostMapping("/addTeamRole")
    public R addTeamRole(
                         @RequestBody UserRoles userRoles
                         ) {
        try {
            boolean add = teamService.addTeamRole(userRoles);
            if (add) {
                return R.ok(String.format("团队%s中角色%s添加成功", userRoles.getTeamId(), userRoles.getRoleName()));
            } else {
                return R.failure("添加失败");
            }
        } catch (Exception e) {
            return R.failure(e.getMessage());
        }
    }
    //获取团队拥有的角色
    @GetMapping("/getTeamRoleList")
    public R getTeamRoleList(@RequestParam Long teamId) {
        try {
            List<UserRoles>  teamRoles= teamService.getTeamRoles(teamId);
            if (teamRoles!=null) {
                return R.ok(teamRoles);
            } else {
                return R.failure("角色获取为空");
            }
        } catch (Exception e) {
            return R.failure(e.getMessage());
        }
    }

    //为用户设置角色
    @PostMapping("/setUserRole")
    public R setUserRole(
                         @RequestParam Long teamId,
                         @RequestParam List<String> userIds,
                         @RequestParam Long roleId
                         ) {
        try {
            boolean add = teamService.setUserRole(teamId, userIds, roleId);
            if (add) {
                return R.ok("角色设置成功");
            } else {
                return R.failure("角色设置失败");
            }
        } catch (Exception e) {
            return R.failure(e.getMessage());
        }
    }

    //为用户设置访问资源权限
    @PostMapping("/setUserResourceRole")
    public R setUserResourceRole(
                                 @RequestParam Long teamId,
                                 @RequestParam List<String> userIds,
                                 @RequestBody UserTeamPermissions userTeamPermissions
                                 ) {
        try {
            boolean add = teamService.setUserResourceRole(teamId, userIds,userTeamPermissions);
            if (add) {
                return R.ok("资源权限设置成功");
            } else {
                return R.failure("资源权限设置失败");
            }
        } catch (Exception e) {
            return R.failure(e.getMessage());
        }

    }

    //展现团队内可见的资源:获取应用
    //获取团队的所有文件夹的ID和名称

    @GetMapping("/getTeamApplyResourcesFiles")
    public R getTeamApplyResourcesFiles(@AuthenticationPrincipal UserDetails userDetails,
                                   @RequestParam Long teamId
                                   ) {
        try {
            User user = (User) userDetails;
            //给出fileID和fileName组成的列表集合
            List<TeamFiles> TeamFiles= teamService.getTeamResourcesFiles(user.getUserId(),teamId);
            return R.ok(TeamFiles);
        } catch (Exception e) {
            return R.failure(e.getMessage());
        }
                                   }




    //根据文件夹ID获取对应List<StoreFlowInfo>，同时允许基于关键词对标签过滤
    @GetMapping("/getTeamApplyResources")
    public R getTeamApplyResources(@AuthenticationPrincipal UserDetails userDetails,
                                   @RequestParam Long FileId,
                                   @RequestParam Long teamId,
                                   @RequestParam(required = false, defaultValue = "") String keyword
                                   ) {
        try {
            User user = (User) userDetails;
            List<StoreFlowInfo> FlowResources= teamService.getTeamApplyResources(user.getUserId(),FileId,teamId,keyword);

            return R.ok();
        } catch (Exception e) {
            return R.failure(e.getMessage());
        }
                                   }



    @GetMapping("/getTeamResourcesApply")
    public R getTeamResourcesApply(@AuthenticationPrincipal UserDetails userDetails,
                                   @RequestParam Long teamId,
                                   @RequestParam(required = false, defaultValue = "") String keyword
                                   ) {
        try {
            User user = (User) userDetails;
            Map<String,List<StoreFlowInfo>> FlowResources= teamService.getTeamResourcesApply(user.getUserId(),teamId,keyword);

            return R.ok();
        } catch (Exception e) {
            return R.failure(e.getMessage());
        }
    }


    //获取个人空间的应用：包括仅个人可见应用和个人创建的团队应用
    //展现团队内可见的资源:获取数据





    //邀请成员



    @GetMapping("/judgeAdmin")
    public R judgeAdmin(@AuthenticationPrincipal UserDetails userDetails,
                        @RequestParam Long teamId
                        ) {
        try {
            User user = (User) userDetails;
            boolean admin = teamService.judgeAdmin(user.getUserId(), teamId);
            if (admin) {
                return R.ok();
            } else {
                return R.failure("未检索到相关team或您不是管理员");
            }
        } catch (Exception e) {
            return R.failure(e.getMessage());
        }
    }

    @GetMapping("/getTeamInfo")
    public R getTeamInfo(@AuthenticationPrincipal UserDetails userDetails,
                                 @RequestParam Long teamId,
                                 @RequestParam Boolean isAdmin
                                 ) {
        try {
            Map<String, String> teamInfo = teamService.getTeamInfo(teamId, isAdmin);
            if (teamInfo != null) {
                return R.ok(null, teamInfo);
            } else {
                return R.failure("未检索到相关team");
            }
        } catch (Exception e) {
            return R.failure(e.getMessage());
        }
    }

    @PutMapping("/updateTeamInfo")
    public R updateTeamInfo(@AuthenticationPrincipal UserDetails userDetails,
                            @RequestParam Long teamId,
                            @RequestBody JsonNode teamInfo
                            ) {
        try {
            boolean updated = teamService.updateTeamInfo(teamId, teamInfo);
            if (updated) {
                return R.ok("更新成功");
            } else {
                return R.failure("更新失败");
            }
        } catch (Exception e) {
            return R.failure(e.getMessage());
        }
    }

}
